package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.adapter.MyMessageAdapter;
import com.jdy.haoduoai.model.LeSysMessage;
import com.jdy.haoduoai.model.LeSysMessageWrapper;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.pulltorefresh.PullToRefreshLayout;
import com.jdy.haoduoai.pulltorefresh.PullToRefreshLayout.OnRefreshListener;
import com.jdy.haoduoai.pulltorefresh.PullableListView;
import com.jdy.haoduoai.rx.util.async.Async;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LePreference;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

//import com.jdy.haoduoai.R;

/**
 * 我的消息
 * 
 * @author Administrator
 * 
 */
public class MyMessageActivity extends BaseActivity implements OnClickListener,
    OnItemClickListener {

  @InjectView(id = R.id.content_views)
  private PullableListView listview;

  @InjectView(id = R.id.emptyview)
  private ImageView emptyview;
  @InjectView(id = R.id.refresh_view)
  private PullToRefreshLayout pullToRefreshLayout;
  @InjectView(id = R.id.bottomlyt)
  private LinearLayout bottomlyt;
  @InjectView(id = R.id.delete, click = true)
  private Button delete;
  @InjectView(id = R.id.select, click = true)
  private Button select;

  private MyMessageAdapter adapter;

  private List<LeSysMessage> mSysMessageList;
  private List<LeSysMessage> mDeleteList;
  private ArrayList<LeSysMessage> mSysMessageAdapterList;
  private LeSysMessageWrapper mLeSysMessageWrapper;

  private int mLastPage = 1;

  private String xml = "";
  private LeUser mLeUser;
  public boolean isrefreshlist = false;

  @Override
  @SuppressLint("InflateParams")
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mymessage);
    setTitle("我的消息");

    LePreference.getInstance().save("clickmymsg", "1"); // 点击‘我的消息’
    mLeUser = LeXiaoXiaoBanApp.getInstance().getUser();
    mSysMessageList = new ArrayList<LeSysMessage>();
    mSysMessageAdapterList = new ArrayList<LeSysMessage>();
    mDeleteList = new ArrayList<LeSysMessage>();

    // 标题栏右上角button
    getbtn_right().setVisibility(View.VISIBLE);
    getbtn_right().setBackgroundResource(R.drawable.edit_btn);
    getbtn_right().setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        if (bottomlyt.isShown()) {
          adapter.setSelectAll(false);
          bottomlyt.setVisibility(View.GONE);
          if (mSysMessageList != null && !mSysMessageList.isEmpty()) {
            for (LeSysMessage ls : mSysMessageList) {
              ls.selected = false; // );
            }
          }
          adapter.setEditor(false);
          adapter.notifyDataSetChanged();
          getbtn_right().setBackgroundResource(R.drawable.edit_btn);
        } else {
          bottomlyt.setVisibility(View.VISIBLE);
          adapter.setEditor(true);
          adapter.notifyDataSetChanged();
          getbtn_right().setBackgroundResource(R.drawable.cancle);
        }
      }
    });

    listview.setOnItemClickListener(this);

    pullToRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
      @Override
      public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        mLastPage = 1;
        isrefreshlist = true;
        loadData(true);
      }

      @Override
      public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        isrefreshlist = false;
        mLastPage++;
        loadData(true);
      }
    });

    loadData(true);
  }

  private void loadData(boolean isShow) {
    // mSysMessageList.clear();
    if (isShow) {
      showloading("");
    }

    Async
        .start(new Func0<ResponseResult>() {
          @Override
          public ResponseResult call() {

            HashMap<String, Object> param_ = new HashMap<String, Object>();
            param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
            param_.put(HttpUtils.TAG_PAGE_I, mLastPage);
            param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

            return HttpUtils.startRequest(HttpUtils.API_URL
                + "/api/2.0/member/message", param_, HttpUtils.TAG_GET_REQUEST);

          }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .filter(new Func1<ResponseResult, Boolean>() {

          @Override
          public Boolean call(ResponseResult arg0) {

            boolean r = (arg0 != null && Tools.isNotEmpty(arg0) && arg0
                .isSuccess());
            if (!r) {
              toastShow("获取系统信息失败");
            }
            return r;
          }
        }).doOnCompleted(new Action0() {

          @Override
          public void call() {
            dismissLoading();

            if (isrefreshlist) {
              mSysMessageList.clear();
            }
            mSysMessageList.addAll(mSysMessageAdapterList);

            if (mLastPage >= 1) {
              if (adapter == null) {
                if (Tools.isEmpty(mSysMessageList)) {
                  adapter = new MyMessageAdapter(MyMessageActivity.this,
                      new ArrayList<LeSysMessage>());
                } else {
                  adapter = new MyMessageAdapter(MyMessageActivity.this,
                      (ArrayList<LeSysMessage>) mSysMessageList);
                  pullToRefreshLayout
                      .refreshFinish(PullToRefreshLayout.SUCCEED);
                }

                listview.setAdapter(adapter);
                listview.setEmptyView(emptyview);
              } else {
                adapter.notifyDataSetChanged();
              }

              if (mSysMessageList != null
                  && mSysMessageList.size() == mLeSysMessageWrapper.total) {
                canLoadMore = false;
                pullToRefreshLayout
                    .refreshFinish(PullToRefreshLayout.LOAD_COMPLETED);
                pullToRefreshLayout
                    .loadmoreFinish(PullToRefreshLayout.LOAD_COMPLETED);
              } else {
                pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
              }

            } else {
              pullToRefreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
              pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.FAIL);
            }

            // mLastPage++;

            isrefreshlist = false;

          }
        }).subscribe(new Action1<ResponseResult>() {

          @Override
          public void call(ResponseResult arg0) {
            if (Tools.isNotEmpty(arg0)) {

              try {
                mLeSysMessageWrapper = JsonSerializer.getInstance()
                    .deserialize(arg0.data, LeSysMessageWrapper.class);
              } catch (Exception e) {
                mLeSysMessageWrapper = null;
              }

              if (mSysMessageAdapterList != null) {
                mSysMessageAdapterList.clear();
              }

              if (mLeSysMessageWrapper != null) {
                if (Tools.isNotEmpty(mLeSysMessageWrapper.data)) {
                  if (mSysMessageAdapterList != null) {
                    mSysMessageAdapterList.clear();
                  }
                  mSysMessageAdapterList = (ArrayList<LeSysMessage>) mLeSysMessageWrapper.data;
                } else {
                  mLastPage--;
                }
              } else {
                mLastPage--;
              }

            }
          }
        });
  }

  private boolean canLoadMore = true;

  private void deleteMessage(final LeSysMessage ls) {
    Async
        .start(new Func0<ResponseResult>() {
          @Override
          public ResponseResult call() {

            HashMap<String, Object> param_ = new HashMap<String, Object>();
            param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
            param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

            return HttpUtils.startRequest(HttpUtils.API_URL
                + "/api/2.0/member/message/" + ls.id, param_,
                HttpUtils.TAG_DELETE_REQUEST);

          }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .filter(new Func1<ResponseResult, Boolean>() {

          @Override
          public Boolean call(ResponseResult arg0) {

            boolean r = (arg0 != null && Tools.isNotEmpty(arg0) && arg0
                .isSuccess());
            // if (r) {
            // toastShow("删除信息成功");
            // }
            return r;
          }
        }).doOnCompleted(new Action0() {

          @Override
          public void call() {
            ++delIndex;
            if (delIndex == deleteItemCount) {
              mSysMessageList.removeAll(mDeleteList);
              adapter.notifyDataSetChanged();
            }
          }
        }).subscribe(new Action1<ResponseResult>() {

          @Override
          public void call(ResponseResult arg0) {

            if (arg0.isSuccess()) {
              toastShow("删除信息成功");
            }

          }
        });
  }

  private int deleteItemCount;

  private int delIndex;

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.delete:
      mDeleteList.clear();

      boolean hasDeleteItem = false;
      deleteItemCount = 0;
      delIndex = 0;

      if (mSysMessageList != null && !mSysMessageList.isEmpty()) {
        for (LeSysMessage ls : mSysMessageList) {
          if (ls.selected) {
            ++deleteItemCount;
          }
        }

        for (LeSysMessage ls : mSysMessageList) {
          if (ls.selected) {
            hasDeleteItem = true;
            mDeleteList.add(ls);
            deleteMessage(ls);
          }
        }
      }

      if (!hasDeleteItem) {
        toastShow("请选择删除条目");
      }
      break;
    case R.id.select:
      if (select.getText().toString().equals("全选")) {
        adapter.setSelectAll(true);
        for (LeSysMessage ls : mSysMessageList) {
          ls.selected = true;
        }

        adapter.notifyDataSetChanged();
        select.setText("取消全选");
      } else if (select.getText().toString().equals("取消全选")) {
        adapter.setSelectAll(false);
        for (LeSysMessage ls : mSysMessageList) {
          ls.selected = false;
        }

        adapter.notifyDataSetChanged();
        select.setText("全选");
      }
      break;
    default:
      break;
    }
  }

  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position,
      long id) {
    if (adapter != null && adapter.isEditor()) {
      CheckBox cbx;
      boolean isChecked = false;

      if (view instanceof CheckBox) {
        cbx = (CheckBox) view;
      } else {
        cbx = (CheckBox) view.findViewById(R.id.radiobtn);
      }

      if (cbx != null) {
        isChecked = cbx.isChecked();
        cbx.setChecked(!isChecked);
      }

      if (mSysMessageList != null && !mSysMessageList.isEmpty()) {
        LeSysMessage ls = mSysMessageList.get(position);
        if (ls != null) {
          ls.selected = !isChecked; // );
        }
      }
    } else {
      LeSysMessage item = mSysMessageList.get(position);
      mSysMessageList.get(position).read = true;
      Intent intent = new Intent();
      intent.setClass(this, MessageDetailsActivity.class);
      Bundle bundle = new Bundle();
      bundle.putSerializable("MessageItem", item);
      intent.putExtras(bundle);
      startActivity(intent);
    }
  }

  @Override
  protected void onResume() {

    if (adapter != null) {
      adapter.notifyDataSetChanged();
    }

    super.onResume();
  }

  /*
   * 下拉刷新
   */
  @SuppressWarnings("unused")
  private class GetDataTask extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
      // HttpClient httpClient = new DefaultHttpClient();
      // HttpGet request = new HttpGet("");
      // HttpConnectionParams.setConnectionTimeout(request.getParams(), 10 *
      // 1000);
      // HttpConnectionParams.setSoTimeout(request.getParams(), 10 * 1000);
      // HttpConnectionParams.setTcpNoDelay(request.getParams(), true);
      // try {
      // xml = httpClient.execute(request, new BasicResponseHandler());
      // } catch (ClientProtocolException e) {
      // e.printStackTrace();
      // } catch (IOException e) {
      // e.printStackTrace();
      // }
      return xml;
    }

    @Override
    protected void onPostExecute(String result) {

      // if (adapter == null) {
      // adapter = new MyMessageAdapter(MyMessageActivity.this, mList);
      // listview.setAdapter(adapter);
      // } else {
      // adapter.notifyDataSetChanged();
      // }
      // pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
      // setView();
      super.onPostExecute(result);
    }
  }

}
